package com.example.jwjg_storage;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;

import android.app.DatePickerDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.graphics.Paint;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;

import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;

import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;


import java.util.ArrayList;
import java.util.Arrays;

import java.util.Calendar;
import java.util.List;


import Util.DBUtil;
import Util.ExcelUtil;
import entity.OperateMessage;
import entity.StorageMessage;
import entity.StorageMessageEx;

public class MainActivity extends AppCompatActivity {
    private  StorageMessage storageMsg=new StorageMessage();


    StorageHerdler sHandler=new StorageHerdler(this);
    OperatorsHerdler oHandler=new OperatorsHerdler(this);
    private LinearLayout columnLeft;
    private LinearLayout columnRight;

    private Context context;
    private Button QrOpen;
    private Button ExcelExport;
    private final static int REQUEST_CODE = 1001;

    Calendar ca = Calendar.getInstance();
    int  mYear = ca.get(Calendar.YEAR);
    int  mMonth = ca.get(Calendar.MONTH);
    int  mDay = ca.get(Calendar.DAY_OF_MONTH);

//    private static final int REQUEST_EXTERNAL_STORAGE = 1;
//    private static String[] PERMISSIONS_STORAGE = {
//            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE
//    };
//
//    private static void verifyStoragmissions(Activity activity) {
//        int permission = ActivityCompat.checkSelfPermission(activity,
//                "android.permission.WRITE_EXTERNAL_STORAGE");
//        int permission1 = ActivityCompat.checkSelfPermission(activity,
//                "android.permission.READ_EXTERNAL_STORAGE");
//        if (permission != PackageManager.PERMISSION_GRANTED || permission1 != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
//        }
//        System.out.println("权限获取");
//    }

    List<String> operatorArray=new ArrayList<>(Arrays.asList("陈建国","陈智涛","耿涛","蒋春宽","李躲发","李秀华","林小红","毛锡民","沙光付","邵锋","宋华",
            "王代兴","王国洪","翁忠明","徐剑云","徐秀龙","徐长春","严祝宏","叶惠剑","叶建祥","叶小龙","叶紫薇","余明明","占小兵","郑二中","郑建清","郑全耀","朱虎"));
    List<OperateMessage> operateMessageList=new ArrayList<>(28);

    /**
     * 接收解析后传过来的数据
     */
    Handler flagHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Boolean flag=false;
            if (msg.obj instanceof Boolean){
                flag=(Boolean)msg.obj;
            }

            if (flag){
                cleanData();
            }
        }
    };


    static class StorageHerdler extends Handler{
        WeakReference<MainActivity> mActivity;

        StorageHerdler(MainActivity activity){
            mActivity=new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            final MainActivity mainActivity=mActivity.get();
            Log.d("导出storage数据:", msg.obj+"");
            List<StorageMessageEx> sArray=new ArrayList<>();
            List<OperateMessage> oArray=new ArrayList<>();
            if (msg.obj instanceof ArrayList<?>){
                for (Object o : (List<?>) ((ArrayList) msg.obj).get(0)) {
                    sArray.add((StorageMessageEx) o);
                }
            }
            if (msg.obj instanceof ArrayList<?>){
                for (Object o : (List<?>) ((ArrayList) msg.obj).get(1)) {
                    oArray.add((OperateMessage) o);
                }
            }



            for (int i = 0; i<sArray.size() ; i++) {

                List otArray =new ArrayList();
                for (int j = 0; j <oArray.size() ; j++) {

                    if (oArray.get(j).getStorageId()==sArray.get(i).getId()){

                        String operatorAndTimes=oArray.get(j).getOperatorName()+":"+oArray.get(j).getOperateTimes();
                        otArray.add(operatorAndTimes);

                    }
                }
//                System.out.println(otArray);
                sArray.get(i).setOperatorAndTimes(otArray);

            }
            Log.d("111", sArray+"");
            String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/AndroidExcelDemo";
//            String filePath = mainActivity.getFilesDir().getPath();
            if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
                System.out.println("存在");
            }


            File file = new File(filePath);
            if (!file.exists()) {
                boolean a=file.mkdirs();
                if (a){
                    System.out.println("成功");
                }else {
                    System.out.println("失败");
                }
            }

            System.out.println(file);
            String excelFileName = "/demo.xlsx";
            File file1=new File(filePath+excelFileName);
            try {
                file1.createNewFile();

            } catch (IOException e) {
                e.printStackTrace();
            }
            String[] title = {"id","条码", "合格数量", "废品数量","入库员","入库日期","创建时间","操作员及次数"};

            System.out.println(filePath);
            filePath = filePath+excelFileName;
            ExcelUtil.initExcel(filePath, title);


            ExcelUtil.writeObjListToExcel(sArray, filePath, mainActivity);


            System.out.println("excel已导出至："  + filePath);




        }
    }

    static class OperatorsHerdler extends Handler{
        WeakReference<MainActivity> mActivity;

        OperatorsHerdler(MainActivity activity){
            mActivity=new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            final MainActivity mainActivity=mActivity.get();
            Log.d("导出数据", msg.obj+"");
            List<String> oArray=new ArrayList<>();
            if (msg.obj instanceof ArrayList<?>){
                for (Object o : (List<?>) msg.obj) {
                    oArray.add((String) o);
                }
            }
//            System.out.println(msg.obj instanceof ArrayList<?>);


            int divideNumber=(int)Math.round(oArray.size()*0.5);
            for (int i = 0; i <divideNumber; i++) {
                final OperateMessage operateMsg=new OperateMessage();
                operateMsg.setOperatorName(mainActivity.operatorArray.get(i));

                TextView tv=new TextView(mainActivity);
                Spinner spinner=new Spinner(mainActivity);
                String []items={"0","1","2","3","4","5","6"};

                ArrayAdapter adapter=new ArrayAdapter<>(mainActivity,android.R.layout.simple_spinner_item,items);
                spinner.setAdapter(adapter);
                spinner.setBackgroundResource(R.drawable.spinner_border);
                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        operateMsg.setOperateTimes(position);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
//                CharSequence charSequence=(CharSequence)spinner.getSelectedItem();
//                System.out.println(charSequence);
                tv.setText(oArray.get(i));
                LinearLayout content=new LinearLayout(mainActivity);
                content.setOrientation(LinearLayout.HORIZONTAL);
                content.addView(tv);
                content.addView(spinner);
                mainActivity.columnLeft.addView(content);
                LinearLayout.LayoutParams tvLayoutParams=(LinearLayout.LayoutParams)tv.getLayoutParams();
                tvLayoutParams.width=200;
                ViewGroup.LayoutParams spLayoutParams=spinner.getLayoutParams();
                spLayoutParams.width=160;


                mainActivity.operateMessageList.add(operateMsg);





            }


            for (int j = divideNumber; j <oArray.size() ; j++) {
                final OperateMessage operateMsg=new OperateMessage();
                operateMsg.setOperatorName(mainActivity.operatorArray.get(j));

                TextView tv=new TextView(mainActivity);
                Spinner spinner=new Spinner(mainActivity);
                String []items={"0","1","2","3","4","5","6"};

                ArrayAdapter adapter=new ArrayAdapter<>(mainActivity,android.R.layout.simple_spinner_item,items);
                spinner.setAdapter(adapter);
                spinner.setBackgroundResource(R.drawable.spinner_border);

                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        operateMsg.setOperateTimes(position);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });

                tv.setText(oArray.get(j));
                LinearLayout content=new LinearLayout(mainActivity);
                content.setOrientation(LinearLayout.HORIZONTAL);
                content.addView(tv);
                content.addView(spinner);
                mainActivity.columnRight.addView(content);
                LinearLayout.LayoutParams tvLayoutParams=(LinearLayout.LayoutParams)tv.getLayoutParams();
                tvLayoutParams.width=200;
                ViewGroup.LayoutParams spLayoutParams=spinner.getLayoutParams();
                spLayoutParams.width=160;


                mainActivity.operateMessageList.add(operateMsg);
            }
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        columnLeft=findViewById(R.id.containerColumn1);
        columnRight=findViewById(R.id.containerColumn2);

        System.out.println(DBUtil.getdateEx());
        context = this;

        QrOpen = (Button) findViewById(R.id.QrOpen);
        QrOpen.setOnClickListener(QrOpenListener);
        ExcelExport=findViewById(R.id.excelBtn);
        ExcelExport.setOnClickListener(ExcelExportListener);

        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);



        new Thread(new Runnable() {
            @Override
            public void run() {
                //这里应该从数据库查询，但为了方便直接写

                Message operatorMsg =Message.obtain();
                operatorMsg.what=1;
                operatorMsg.obj=operatorArray;
                oHandler.sendMessage(operatorMsg);

            }
        }).start();

        //定时器
//        Timer timer=new Timer();
//        TimerTask task=new TimerTask() {
//            @Override
//            public void run() {
//                try{
//                    Log.d("导入数据：", storageList+"");
//                }catch (Exception e){
//
//                }
//            }
//        };
//        timer.schedule(task,0,100);




         EditText codeText=findViewById(R.id.codeText);

        codeText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 输入前的监听

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 输入的内容变化的监听
                Log.d("条码：", s+"");

                if (s.length()>0){
                    storageMsg.setCode(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 输入后的监听
            }
        });


        EditText qualfiedNumberText=findViewById(R.id.qualifiedNumberText);
        qualfiedNumberText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.d("合格数量：", s+"");
                if (s.length()>0){
                    storageMsg.setQualifiedNumber(Integer.parseInt(s.toString()));
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        EditText unQualfiedNumberText=findViewById(R.id.unQualifiedNumberText);
        unQualfiedNumberText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.d("废品数量：", s+"");
                if (s.length()>0){
                    storageMsg.setUnQualifiedNumber(Integer.parseInt(s.toString()));
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        RadioGroup rg_inout=findViewById(R.id.rg_inout);
        rg_inout.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rb=findViewById(checkedId);
                Log.d("选择：", rb.getText()+"");
                storageMsg.setInOut(rb.getText().toString());
            }
        });

        RadioGroup rg_storage_man=findViewById(R.id.rg_storage_man);
        rg_storage_man.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton rb=findViewById(checkedId);
                Log.d("入库员：", rb.getText()+"");
                storageMsg.setStorage_man(rb.getText().toString());
            }
        });

        Button confirmBtn=findViewById(R.id.confirmBtn);
        confirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText codeText=findViewById(R.id.codeText);
                EditText qualfiedNumberText=findViewById(R.id.qualifiedNumberText);
                EditText unQualfiedNumberText=findViewById(R.id.unQualifiedNumberText);
                RadioGroup rg_inOut=findViewById(R.id.rg_inout);
                RadioGroup rg_storage_man=findViewById(R.id.rg_storage_man);
                RadioButton rb_inOut=findViewById(rg_inOut.getCheckedRadioButtonId());
                RadioButton rb_storage_man=findViewById(rg_storage_man.getCheckedRadioButtonId());


                if (codeText.getText().length()==0){
                    System.out.println("code不能为空");
                    Toast toast=Toast.makeText(context,"code不能为空",Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER,0,-250);
                    toast.show();
                }else if(qualfiedNumberText.getText().length()==0){
                    System.out.println("qualfiedNumberText不能为空");
                    Toast toast=Toast.makeText(context,"qualfiedNumberText不能为空",Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER,0,-250);
                    toast.show();
                }else if(unQualfiedNumberText.getText().length()==0){
                    System.out.println("unQualfiedNumberText不能为空");
                    Toast toast=Toast.makeText(context,"unQualfiedNumberText不能为空",Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER,0,-250);
                    toast.show();
                }else if(rb_inOut==null){
                    System.out.println("rg_inOut不能为空");
                    Toast toast=Toast.makeText(context,"rg_inOut不能为空",Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER,0,-250);
                    toast.show();
                }else if(rb_storage_man==null){
                    System.out.println("rg_storage_man不能为空");
                    Toast toast=Toast.makeText(context,"rg_storage_man不能为空",Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER,0,-250);
                    toast.show();
                }else {
                    Log.d("入库录入信息：", storageMsg.toString());

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println(operateMessageList);

                            if (DBUtil.insert(storageMsg)>0){
                                int storageId=DBUtil.queryIdByCode(storageMsg.getCode());
                                for (int i = 0; i <operateMessageList.size() ; i++) {
                                    operateMessageList.get(i).setStorageId(storageId);
                                }
                                if(DBUtil.insertOM(operateMessageList)>0){
                                    Looper.prepare();
                                    Toast toast=Toast.makeText(context,"插入成功",Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER,0,-250);
                                    toast.show();
                                    Message msg=new Message();
                                    msg.what=1;
                                    msg.obj=true;
                                    flagHandler.sendMessage(msg);
                                    Looper.loop();



                                }
                            }


                        }
                    }).start();

                }
            }
        });
    }

    private View.OnClickListener QrOpenListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //打开扫描界面
            IntentIntegrator intentIntegrator = new IntentIntegrator(MainActivity.this);
            intentIntegrator.setOrientationLocked(false);
            intentIntegrator.setCaptureActivity(QRActivity.class); // 设置自定义的activity是QRActivity
            intentIntegrator.setRequestCode(REQUEST_CODE);
            intentIntegrator.initiateScan();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            IntentResult scanResult = IntentIntegrator.parseActivityResult(resultCode, data);
            final String qrContent = scanResult.getContents();
            EditText codeText=findViewById(R.id.codeText);
            codeText.setText(qrContent);
//            Toast.makeText(context, "扫描结果:" + qrContent, Toast.LENGTH_SHORT).show();
        }
    }

    private View.OnClickListener ExcelExportListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

//            LayoutInflater inflater = getLayoutInflater();
//            View layout = inflater.inflate(R.layout.query_storage, (ViewGroup) findViewById(R.id.dialog));
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

                    View dialogView = getLayoutInflater().inflate(R.layout.query_storage,null);
                     //获取两个文本编辑框
                     final TextView startDate =  dialogView.findViewById(R.id.startDate);
                     final TextView endDate =  dialogView.findViewById(R.id.endDate);
                     startDate.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG );
                     endDate.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG );
                     builder.setView(dialogView);//设置query_storage为对话提示框
                     builder.setCancelable(false);//设置为不可取消
                     startDate.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
//                             DatePickerDialog.Builder dateBuilder=new DatePickerDialog.Builder(MainActivity.this);
//                             View datePickerView=getLayoutInflater().inflate(R.layout.date_picker,null);
//                             dateBuilder.setView(datePickerView);
//                             dateBuilder.show();
                         }
                     });
                      startDate.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this,
                                    new DatePickerDialog.OnDateSetListener() {

                                        @Override
                                        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        //                                             mYear = year;
        //                                             mMonth = month+1;
        //                                             mDay = dayOfMonth;
                                            startDate.setText(year+"-"+month+1+"-"+dayOfMonth);
                                        }
                                    },
                                    mYear, mMonth, mDay);
                            datePickerDialog.show();
                        }
                      });


                     endDate.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this,
                                     new DatePickerDialog.OnDateSetListener() {

                                         @Override
                                         public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
//                                             mYear = year;
//                                             mMonth = month+1;
//                                             mDay = dayOfMonth;
                                             endDate.setText(year+"-"+month+1+"-"+dayOfMonth);
                                         }
                                     },
                                     mYear, mMonth, mDay);
                             datePickerDialog.show();
                         }
                     });
                     builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                        }
                     });
                     builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                         @Override
                         public void onClick(DialogInterface dialog, int which) {
                             System.out.println(startDate.getText());
                             System.out.println(endDate.getText());
                            // 导出数据
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    List excelList=new ArrayList();
                                    excelList.add(DBUtil.QueryWhereDate(startDate.getText().toString(),endDate.getText().toString()));
                                    excelList.add(DBUtil.QueryOperator());

                                    Message storageMsg =Message.obtain();
                                    storageMsg.what=1;
                                    storageMsg.obj=excelList;
                                    sHandler.sendMessage(storageMsg);

                                }
                            }).start();
                             dialog.dismiss();
                         }
                     });

                     builder.show();




        }


    };

    private  void cleanData(){
        EditText codeText=findViewById(R.id.codeText);
        codeText.setText("");
        EditText qualfiedNumberText=findViewById(R.id.qualifiedNumberText);
        qualfiedNumberText.setText("");
        EditText unQualfiedNumberText=findViewById(R.id.unQualifiedNumberText);
        unQualfiedNumberText.setText("");
        int divideNumber=(int)Math.round(operatorArray.size()*0.5);
        System.out.println(divideNumber);
        for (int i = 0; i <divideNumber ; i++) {
            LinearLayout content=(LinearLayout) columnLeft.getChildAt(i);
//            Log.d("LinearLayoutLeft", content+"");
            Spinner spinner=(Spinner)content.getChildAt(1);
            spinner.setSelection(0);
        }
        for (int i = 0; i <operatorArray.size()-divideNumber ; i++) {
            LinearLayout content=(LinearLayout) columnRight.getChildAt(i);
//            Log.d("LinearLayoutRight", content+"");
            Spinner spinner=(Spinner)content.getChildAt(1);
            spinner.setSelection(0);
        }


    }


    @Override
    protected void onStart() {

        super.onStart();
        Button btn=findViewById(R.id.checkBtn);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                cleanData();

            }
        });
    }


}
